import urllib, urllib2, cookielib
from BeautifulSoup import BeautifulSoup

class IEDProxy(object):
	'''A proxy class that handles the low-level communication with the flashchat'''
	
	IED_LOGIN_PAGE = 'http://ied.bayrem-cherif.com/index.php'
	
	IED_CHAT_ROOT = 'http://ied.bayrem-cherif.com/chat/'
	
	INDEX_PAGE, LOGOUT_PAGE, XML_PAGE = 'index.php', 'dologout.php', 'getxml.php'
	
	communication_id = '' # 32-digit hexadecimal string used by the server to identify the user.
	
	last_msg_id = 0 # id of the last received message (keeps incrementing)
	
	def __init__(self):
		'''Sets up the cookiejar and install cookie handling for urllib2.open()'''
		cj = cookielib.LWPCookieJar()
		opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
		urllib2.install_opener(opener)
	
	def get_http_handle(self, url, data=None):
		'''Utility method that returns a http handle for the given url and post data'''
		if not data:
			req = urllib2.Request(url)
		else:
			req = urllib2.Request(url, urllib.urlencode(data))
		return urllib2.urlopen(req)
	
	def get_http_response(self, url, data=None):
		'''Utility function that returns the http response (text) for the given url and post data'''
		handle = self.get_http_handle(url, data)
		return_value = handle.read()
		handle.close()
		return return_value
	
	def fetch_login_data(self):
		'''Retreives data that we need to log in (such as a 33-digit identifier the use of which is undertemined)'''
		soup = BeautifulSoup(self.get_http_response(self.IED_LOGIN_PAGE))
		
		#Basically, we retreive all the html hidden inputs and transform them into a dictionary
		hinputs = soup.form.findAll('input', type="hidden")
		return dict([(h['name'], h['value']) for h in hinputs])
	
	def login(self, username, password):
		'''Attempt to connect to the chat'''
		login_data = self.fetch_login_data()
		login_data.update({'username': username, 'passwd': password})
		self.get_http_handle(self.IED_LOGIN_PAGE, login_data).close() # Initiate the general auth cookie
		self.get_http_handle(self.IED_CHAT_ROOT + self.INDEX_PAGE).close() # Initiate the flashchat auth cookie
		
		#TODO: be able to determine if the login/password are correct by examining the http response
		return True
	
	def logout(self):
		'''Disconnects from the chat'''
		self.get_http_handle('%s%s?id=%s' % (self.IED_CHAT_ROOT, self.LOGOUT_PAGE, self.communication_id)).close()
		return True
	
	def request(self, data, handler_callback):
		'''Sends an a POST request to the server, passes the value of the response to the given handler and returns the handler return value'''
		post_data = {'id': self.communication_id, 'b': self.last_msg_id + 1}
		post_data.update(data)
		return handler_callback(self.get_http_response(self.IED_CHAT_ROOT + self.XML_PAGE, post_data))
